/**
 * TimeAgoTag.java
 * com.sftz.framework.tag
 * Copyright (c) 2017, 北京科技有限公司版权所有.
*/

package com.sftz.framework.mvc.tag;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import lombok.Data;
import lombok.EqualsAndHashCode;

import com.uxuexi.core.common.util.Util;

/**
 * 过去多少时间的tag，用于展示刚刚，几分钟前，几小时前
 * <p>
 * @author   朱晓川
 * @Date	 2017年11月16日
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class TimeAgoTag extends SimpleTagSupport {

	private final static long MINUTE = 60 * 1000;// 1分钟  
	private final static long HOUR = 60 * MINUTE;// 1小时  
	private final static long DAY = 24 * HOUR;// 1天   
	private final static long MONTH = 31 * DAY;// 月   
	private final static long YEAR = 12 * MONTH;// 年   

	private Timestamp datetime;

	@Override
	public void doTag() throws JspException, IOException {
		JspWriter out = getJspContext().getOut();
		createTree(out);
		super.doTag();
	}

	private void createTree(final JspWriter out) throws IOException {
		String content = getTimeFormatText(datetime);
		if (Util.isEmpty(content)) {
			return;
		}
		out.print(content);//输出结尾
	}

	public static String getTimeFormatText(Date date) {
		if (date == null) {
			return null;
		}
		long diff = System.currentTimeMillis() - date.getTime();
		long r = 0;
		if (diff > YEAR) {
			r = (diff / YEAR);
			return r + "年前";
		}
		if (diff > MONTH) {
			r = (diff / MONTH);
			return r + "个月前";
		}
		if (diff > DAY) {
			r = (diff / DAY);
			return r + "天前";
		}
		if (diff > HOUR) {
			r = (diff / HOUR);
			return r + "小时前";
		}
		if (diff > MINUTE) {
			r = (diff / MINUTE);
			return r + "分钟前";
		}
		return "刚刚";
	}
}
